package com.hp.gateway_service.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 自定义全局过滤器，用于用户权限验证
 */
@Slf4j
@Component
public class AuthenticationFilter implements GlobalFilter, Ordered {

    @Value("${server.port}")
    private Integer port;

    //过滤请求和响应
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获得请求和响应
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //获得请求参数 如果有token=123456 就表示登录
        String token = request.getQueryParams().getFirst("token");
        log.info("port===>"+port);
//        log.info("url==>"+request.getURI());
//        log.info("token==>"+token);
//        if(!"123456".equals(token)){
//            //如果没有参数token=123456，拒绝访问
//            response.setStatusCode(HttpStatus.UNAUTHORIZED);
//            String msg = "Request Denied!!";
//            DataBuffer wrap = response.bufferFactory().wrap(msg.getBytes());
//            return response.writeWith(Mono.just(wrap));
//        }
        //如果有就放行
        return chain.filter(exchange);
    }

    //返回过滤器顺序，越小越靠前
    @Override
    public int getOrder() {
        return 0;
    }
}
